import { defineStore } from 'pinia';
import { useRoute } from 'vue-router';
import * as Utils from '@/utils/adapter';
import * as Api from '@/api/processClient/processClient';
import type { Ref } from 'vue';
import type * as StoreType from './type';
import type * as ApiType from '@/api/processClient/processClient.d';
import { toRaw } from 'vue';
import type * as PHStoreType from '../processHeader/type';

const useProcessData = defineStore('PrData', {
  // persist: true,
  state: (): StoreType.PrDataState => ({
    taskId: 0,
    userId: 0,
    seriesList: [],
    sarIdList: [],
    index: 0,
    imageIndex: 0,
    imgResult: [],
    seriesResult: {} as ApiType.SeriesResultResponse,
    seriesNameResult: {} as ApiType.SeriesNameResponse,
    discardList: [] as ApiType.DiscardConfig[],
    toolMap: new Map(),
    doctorScrMap: new Map(),
    seriesCompMap: new Map(),
    samllSignMap: new Map(),
    typeMap: new Map(),
    doctorIdMap: new Map(),
    doctorIdList: [],
    dataList: [],
    toolListMap: new Map(),
    currentLesion: {} as ApiType.AuditTaskImageResultList,
    lesionResultList: [] as PHStoreType.Lesion[],
    lesionEnum: {} as { [x: string | number]: string },
    lesionMap: new Map(),
    bigSignObj: {} as PHStoreType.Sign,
    imageGroupMap: new Map(),
    dictList: [],
    loading: true,
  }),
  getters: {
    imageIds: (state: StoreType.PrDataState): ApiType.ImageIds[] => {
      const ids: ApiType.ImageIds[] = state.imgResult.map((item:ApiType.TranFerResponseList, index: number) => {
        return {
          imageId: item.urlWAN,
          isActive: index === state.imageIndex,
        }
      });
      return ids;
    }
  },
  actions: {
    setLoading(isLoading: boolean){
      this.loading = isLoading;
    },
    setLesionResultListActive(uuid: string){
      this.lesionResultList.forEach((item:any)=> {
        let isVisible = false;
        item.viewList.forEach((subItem:any) => {
          if( subItem.lesionData.uuid === uuid ){
            isVisible = true;
            subItem.lesionData.isCurrent = true;
          } else {
            subItem.lesionData.isCurrent = false;
          }
        })
        item.isVisible = isVisible;
      })
    },
    delLesionItem(imageId:number){
      this.lesionResultList.forEach((item:any) => {
        item.isVisible = false;
        item.lesionList.forEach((subItem:any, subIndex: number)=> {
          subItem.forEach((thirdItem:any)=> {
            if(thirdItem.imageId === imageId){
              item.lesionList.splice(subIndex, 1);
            }
          })
        })
        item.viewList.map((subItem:any, index: number)=> {
          subItem.lesionData.isCurrent = false;
          if (subItem.lesionData.approveLeisonId === imageId) {
            item.viewList.splice(index, 1);
            // if (item.viewList.length > 1) {
            //   // 长度不是最后一个
            //   item.viewList[item.viewList.length - 1].lesionData.isCurrent = true;
            // } else {
            //   // 长度是最后一个时聚焦序列征象
            // }
          }
        })
      });
    },
    setCurrentLesion(item: ApiType.AuditTaskImageResultList){
      this.currentLesion = item;
    },
    // 通过路由获取任务id和用户id
    getParams(routeProps?: any) {
      let route;
      if (!routeProps) {
        route = useRoute();
      } else {
        route = routeProps;
      }
      // 设置token
      localStorage.setItem('accessToken', route.query.token as string);
      // 获取用户id和任务id
      this.taskId = +(route.query.taskId as string);
      this.userId = +(route.query.userId as string);
      const params = {
        taskId: this.taskId,
        userId: this.userId
      }
      this.getSeries(params, route);
    },
    // 获取序列集合
    async getSeries(params: ApiType.SeriesParams, routeProps?: any) {
      try {
        let route;
        if (!routeProps) {
          route = useRoute();
        } else {
          route = routeProps;
        }
        // 初始获取字典
        const dictParams = {
          value: null
        };
        const dictList = await Api.getDict(dictParams);
        const tempArr = dictList && dictList.data.filter((item: { id: number; }) => item.id === 9)[0];
        this.dictList = tempArr.children.map((item: { id: any; name: any; value: any; }) => ({id: item.id, name: item.name, value: item.value}));
        // if(route.query.viewType !== 'all'){
        //   this.index = 0;
        // };
        let seriesRes;
        if(route.query.type === 'create'){
          //开始任务
          seriesRes = await Api.getSeries(params);
          this.seriesList = seriesRes.data.seriesList.map(item => item.series);
          this.sarIdList = seriesRes.data.sarIdList;
        } else {
          let serialNumberList:any = [];
          if (route.query.viewType === 'all') {
            const seriesParams = {
              page: 1,
              pageSize: 10000,
              reset: true,
              serialNumber: '',
              taskId: params.taskId,
              userId: route.query.submitUserId || params.userId,
            };
            const result:any = await Api.getSeiesList(seriesParams);
            serialNumberList = result.data.list.map((item:any) => item.serialNumber);
            this.seriesList = result.data.list.map((item:any) => item.serialNumber.split("-")[0]);
          } else {
            if (route.query.serialNumber) {
              serialNumberList = [(route.query.serialNumber as string)];
              this.seriesList = [(route.query.serialNumber as string).split('-')[0]];
            };
          };
          const model =  {
            serialNumber: route.query.serialNumber || serialNumberList[this.index],
            type: "TASK",
            userId: route.query.submitUserId || params.userId,
            id: params.taskId,
          }
          seriesRes = await Api.seriesResultSearch(model);
          this.sarIdList = seriesRes.data.list.map((item:any) => item.id);
        }
        // 调用获取审核结果接口
        const resultParams = {
          series: this.seriesList[this.index],
          taskId: Number(this.taskId)
        };
        const dataResult = await Api.getSeriesResult(resultParams);
        this.seriesResult = dataResult.data;
        //后端可能重复，可能没有98，99
        dataResult.data.discardConfig.push({name:'序列加载异常',value:'98'})
        dataResult.data.discardConfig.push({name:'其他',value:'99'})
        // 获取废片原因集合
        this.discardList = dataResult.data.discardConfig.filter((item,index,arr)=>arr.findIndex((it)=>it.value ===item.value) === index);//去重
        this.imgResult = [];
        // 调用获取图片接口
        const tranferObj: {[x: string]: string} = {};
        tranferObj.seriesInstanceUID = this.seriesList[this.index];
        const tranferParams = {
          client: 'B',
          method: '/v1/series/read',
          params: JSON.stringify(tranferObj),
          service: 'DR'
        };
        let tranferTypeResult:any = {}
        try{
          tranferTypeResult = await Api.getTranfer(tranferParams);
        }catch(e){
          this.setLoading(false);
        }
        tranferObj.fileType = tranferTypeResult.data ? tranferTypeResult.data.fileType : 'JPG';
        tranferParams.method = '/v1/image/query';
        tranferParams.params = JSON.stringify(tranferObj);
        const tranferResult = await Api.getTranfer(tranferParams);
        this.imgResult = tranferResult.data.list;
        this.refreshData();
        // 获取序列名称
        // const seriesNameRes = await Api.getSeriesName(String(this.taskId))
        // this.seriesNameResult = seriesNameRes.data;

        // const map = Utils.getDataMap({ seriesList: this.seriesList, sarIdList: this.sarIdList, ...this.seriesNameResult, ...this.seriesResult }, true, this.index);
        // this.$state = {...this.$state, ...map};
        // console.log(this.$state, 'dataMap数据结果');
        this.setLoading(false);
      } catch (error: any) {
        console.log(error);
        this.setLoading(false);
        this.imgResult = [];
        if (error.code === 1301) {
          this.refreshData();
        }
      };
    },
    // 切换上一个序列
    getDecreaseCurrent() {
      if (this.hasPrev()) {
        // const index = --this.index;
        // this.getParams(ref(true));
        return this.seriesList[--this.index];
      };
      return null;
    },
    // 切换下一个序列
    getIncreaseCurrent() {
      if (this.hasNext()) {
        // const index = ++this.index;
        // this.getParams(ref(true));
        return this.seriesList[++this.index];
      };
      return null;
    },
    hasNext() {
      if (this.index >= this.seriesList.length) {
        return false;
      };
      return true;
    },
    hasPrev() {
      if (this.index <= 0) {
        return false;
      };
      return true;
    },
    async refreshData() {
      // 获取序列名称
      const seriesNameRes = await Api.getSeriesName(String(this.taskId))
      this.seriesNameResult = seriesNameRes.data;

      const map = Utils.getDataMap({ seriesList: this.seriesList, sarIdList: this.sarIdList, ...this.seriesNameResult, ...this.seriesResult }, true, this.index);
      this.$state = {...this.$state, ...map};
    },
    refreshInterface(route: any) {
      this.getParams(route);
    }
  }
});

export default useProcessData;